# -*- coding: utf-8 -*- 
# @Time : 2020-12-08 22:41 
# @Author : derek.zhang 
# @File : password_view.py 
# @Software: PyCharm
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.shortcuts import render
from django.views.decorators.http import require_http_methods

from manabe.forms import ChangEmailForm, ChangePwdForm


@require_http_methods(["GET","POST"])
def change_email(request):
    if request.method == "GET":
        form = ChangEmailForm()
        return render(request, 'account/change_email.html',
                      {'form': form,
                       'current_page_name': '更改邮箱',
                       'email': User.objects.get(username= request.user.username).email})
    else:
        error = []
        form = ChangEmailForm(request.POST)
        if form.is_valid():
            username = request.user.username
            new_email = request.POST['new_email']
            User.objects.filter(username= request.user.username).update(email=new_email)
            # 更改后的邮箱
            email = User.objects.get(username=request.user.username).email
            # 给个标记用于前端显示
            change_email_success = True
            return render(request, 'account/change_email.html',locals())
        else:
            error.append('两次新邮箱不匹配，请重新输入')
            email = User.objects.get(username=request.user.username).email
            return render(request, 'account/change_email.html', locals())


@require_http_methods(["GET","POST"])
def change_password(request):
    if request.method == 'GET':
        form = ChangePwdForm()
        return render(request, 'account/change_password.html',{
            'form': form,
            'current_page_name': '更改密码'
        })
    else:
        error = []
        form = ChangePwdForm(request.POST)
        if form.is_valid():
            username = request.user.username
            oldpassword = request.POST.get('oldpassword', '')
            user = authenticate(usernane= username,password = oldpassword)
            if user is not None and user.is_active:
                newpassword1 = request.POST.get('newpassword1', '')
                # 更新密码的 django 实现
                user.set_password(newpassword1)
                user.save()
                return render(request , 'account/change_password.html', {'changepwd_success':True})
            else:
                error.append('原密码输入错误')
                return render(request, 'account/change_password.html', locals())
        else:
            error.append('两次密码不匹配，请重新输入')
            return render(request, 'account/change_password.html', locals())